package com.tlgen.modules.vocation.service.impl;

import com.tlgen.common.utils.FileUtil;
import com.tlgen.common.utils.PageUtil;
import com.tlgen.common.utils.QueryHelp;
import com.tlgen.common.utils.ValidationUtil;
import com.tlgen.modules.vocation.domain.HomeFile;
import com.tlgen.modules.vocation.repository.HomeFileRepository;
import com.tlgen.modules.vocation.service.HomeFileService;
import com.tlgen.modules.vocation.service.dto.HomeFileDto;
import com.tlgen.modules.vocation.service.dto.HomeFileQueryCriteria;
import com.tlgen.modules.vocation.service.mapper.HomeFileMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Service
@CacheConfig(cacheNames = "HomeFile")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class HomeFileServiceImpl implements HomeFileService {

    private final HomeFileRepository homeFileRepository;

    private final HomeFileMapper homeFileMapper;

    @Value("${file.homefile}")
    private String homefile;

    public HomeFileServiceImpl(HomeFileRepository homeFileRepository, HomeFileMapper homeFileMapper) {
        this.homeFileRepository = homeFileRepository;
        this.homeFileMapper = homeFileMapper;
    }

    /**
     * 不带条件分页查询
     * @param pageable 分页参数
     * @return
     */
    @Override
    @Cacheable
    public Object queryAll(Pageable pageable) {
        return homeFileMapper.toDto(homeFileRepository.findAll(pageable).getContent());
    }


    /**
     * 带条件分页查询
     * @param criteria 条件
     * @param pageable 分页参数
     * @return
     */
    @Override
    @Cacheable
    public Object queryAll(HomeFileQueryCriteria criteria, Pageable pageable) {
        Page<HomeFile> page = homeFileRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(homeFileMapper::toDto));
    }

    /**
     * 带条件不分页查询
     * @param criteria 条件
     * @return
     */
    @Override
    @Cacheable
    public List<HomeFileDto> queryAll(HomeFileQueryCriteria criteria) {
        return homeFileMapper.toDto(homeFileRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    /**
     * 新增
     * @param resources /
     * @return
     */
    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public HomeFileDto create(HomeFile resources) {
        return homeFileMapper.toDto(homeFileRepository.save(resources));
    }

    /**
     * 编辑
     * @param resources /
     */
    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void update(HomeFile resources) {
        HomeFile homeFile = homeFileRepository.findById(resources.getId()).orElseGet(HomeFile::new);
        ValidationUtil.isNull(homeFile.getId(),"HomeFile","id",resources.getId());

        homeFile.setRealName(resources.getRealName());
        homeFile.setPath(resources.getPath());
        homeFile.setCreateTime(resources.getCreateTime());
        homeFile.setSize(resources.getSize());
        homeFileRepository.save(homeFile);
    }

    /**
     * 根据Id查询
     * @param id /
     * @return
     */
    @Override
    @Cacheable(key = "#p0")
    public HomeFileDto findById(long id) {
        HomeFile HomeFile = homeFileRepository.findById(id).orElseGet(HomeFile::new);
        ValidationUtil.isNull(HomeFile.getId(),"HomeFile","id",id);
        return homeFileMapper.toDto(HomeFile);
    }

    /**
     * 删除
     * @param ids /
     */
    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<Long> ids) {
        for (Long id : ids) {
            homeFileRepository.deleteById(id);
        }
    }

    /**
     * 导出数据
     * @param response /
     * @throws IOException
     */
    @Override
    public void download(List<HomeFileDto> HomeFileDtos, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (HomeFileDto homeFileDto : HomeFileDtos) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("文件名称", homeFileDto.getRealName());
            map.put("文件路径", homeFileDto.getPath());
            map.put("创建时间", homeFileDto.getCreateTime());
            map.put("文件大小", homeFileDto.getSize());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    /**
     * 上传附件
     * @param multipartFile
     */
    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void uploadFile(MultipartFile multipartFile) {
        File file = FileUtil.upload(multipartFile, homefile);
        assert file != null;
        HomeFile HomeFile = new HomeFile(file.getName(), file.getPath(), FileUtil.getSize(multipartFile.getSize()));
        homeFileRepository.save(HomeFile);
    }


}
